package cn.tedu.jdbc;

import java.sql.*;
import java.util.Scanner;

public class Test3 {
    public static void main(String[] args)  {
        method();
    }
    public static  Connection get() throws Exception {

        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql:///db1?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url, "root", "root");
       return conn;
    }
    private static void method()  {
        Connection c=null;
        ResultSet r = null;
        PreparedStatement P=null;
        try{
            c=get();
            String sql="select * from user2 where name=? and password=?";
       P =c.prepareStatement(sql);//保护sql不被攻击注入
            //String sql ="select * from user2 where name='asd' and password='123'";//写死了
            String user = new Scanner(System.in).nextLine();//用户输入jack'#
            String pwd = new Scanner(System.in).nextLine();
            //String sql="select * from user2 where name='"+user+"' and password='"+pwd+"'";
            P.setString(1,user);
            P.setString(2,pwd);
            r = P.executeQuery();
            if (r.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            release(c,r,P);
        }

    }
    public static void   release ( Connection c, ResultSet r, PreparedStatement P){
        if (r!=null&&c!=null&&P!=null){
            System.out.println("资源释放");
            try{
                    r.close();
                    c.close();
                    P.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}
